package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    static SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "mybatis-conﬁg.xml";
// 1. 加载本地的核心配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
// 2. 创建sessionFactory
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder =
                    new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //创建sqlSession
    public static SqlSession createSqlSession() {
        return sqlSessionFactory.openSession(false);//关闭自动提交；开启事务
    }

    //关闭sqlSession
    public static void closeSqlSession(SqlSession sqlSession) {
        sqlSession.close();
    }
}